﻿function CallAjax(searchText, startWith, searchUrl) {
    // variables
    this._searchText = searchText;
    this._startWith = startWith;
    this._searchUrl = searchUrl;
    // methods
    this.search = search;
    this.searchWithTextAndStart = searchWithTextAndStart;
    this.searchWithText = searchWithText;
    this.failResult = failResult;

    function search() {
        if (this._startWith != '' && isNaN(this._startWith) == false) {
            this.searchWithTextAndStart();
        } else {
            this.searchWithText();
        }
    }

    function searchWithTextAndStart() {
        $.ajax({
            type: "POST",
            async: true,
            url: this._searchUrl,
            data: {
                'searchText': this._searchText,
                'startWith': this._startWith
            },
            dataType: "json",
            success: function (html) {
                $('#placeHolder').html('');
                $('#placeHolder').append(html.SubView);
            },
            error: function (error) {
                this.failResult();
            }
        }); //end ajax call
    }

    function searchWithText() {
        $.ajax({
            type: "POST",
            async: true,
            url: this._searchUrl,
            data: {
                'searchText': this._searchText,
                'startWith': -1
            },
            dataType: "json",
            success: function (html) {
                $('#placeHolder').html('');
                $('#placeHolder').append(html.SubView);
            },
            error: function (error) {
                this.failResult();
            }
        }); //end ajax call
    }

    function failResult() {
        alert('fail: ' + error);
    }
}